import { Mark, mergeAttributes, markInputRule, markPasteRule } from '@tiptap/core';

const starInputRegex = /(?:^|\s)((?:\*\*)((?:[^*]+))(?:\*\*))$/;
const starPasteRegex = /(?:^|\s)((?:\*\*)((?:[^*]+))(?:\*\*))/g;
const underscoreInputRegex = /(?:^|\s)((?:__)((?:[^__]+))(?:__))$/;
const underscorePasteRegex = /(?:^|\s)((?:__)((?:[^__]+))(?:__))/g;
const Spannode = Mark.create({
    name: 'spannode',
    priority: 2023,
    addOptions() {
        return {
            HTMLAttributes: {},
        }
    },
    // group: 'inline',
    // content: 'inline*',
    parseHTML() {
        return [
            { tag: `span[data-type="${this.name}"]`, },
        ]
    },
    renderHTML({ HTMLAttributes }) {
        return ['span', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]
    },
    addCommands() {
        return {
            // setSpannode: () => ({ commands }) => {
            //     return commands.setNode(this.name)
            // },
            setSpannode: () => ({ commands }) => {
                return commands.setMark(this.name);
            },
            toggleSpannode: () => ({ commands }) => {
                return commands.toggleMark(this.name);
            },
            unsetSpannode: () => ({ commands }) => {
                return commands.unsetMark(this.name);
            },
        }
    },
    addKeyboardShortcuts() {
        return {
            'Mod-Enter': () => this.editor.commands.toggleSpannode(),
        }
    },
    addInputRules() {
        return [
            markInputRule({
                find: starInputRegex,
                type: this.type,
            }),
            markInputRule({
                find: underscoreInputRegex,
                type: this.type,
            }),
        ];
    },
    addPasteRules() {
        return [
            markPasteRule({
                find: starPasteRegex,
                type: this.type,
            }),
            markPasteRule({
                find: underscorePasteRegex,
                type: this.type,
            }),
        ];
    },
});

export { Spannode, Spannode as default, starInputRegex, starPasteRegex, underscoreInputRegex, underscorePasteRegex };

